package org.example.SolutionNew007;

import java.util.Deque;
import java.util.LinkedList;

public class StackSolution002 {
    public static void main(String[] args) {
         MinStack1 minStack = new MinStack1();

    }
}

class MinStack {
    //两个栈，多维护一个单调栈
    Deque<Integer> xStack;
    Deque<Integer> minStack;

    public MinStack() {
        xStack = new LinkedList<>();
        minStack = new LinkedList<>();
        minStack.push(Integer.MAX_VALUE);
    }

    public void push(int val) {
        xStack.push(val);
        minStack.push(Math.min(val, minStack.peek()));
    }

    public void pop() {
        xStack.pop();
        minStack.pop();
    }

    public int top() {
        return xStack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}

//这个是不创建额外单调栈的方法，直接用min参与元素构成
class MinStack1 {
    Deque<Long> minStack;
    int min=0;

    public MinStack1() {
        minStack = new LinkedList<>();
    }

    public void push(int val) {
        if (minStack.isEmpty()) {
            minStack.push(0L);
            min = val;
        }else{
            minStack.push(Long.valueOf(val)-min);
            min = Math.min(min, val);
        }
    }

    public void pop() {
        Long tmp=minStack.pop();
        if(tmp<0){
            min=(int) (min-tmp);
        }
    }

    public int top() {
        if(minStack.peek()<0){
            return min;
        }else{
            return (int)(minStack.peek()+min);
        }
    }

    public int getMin() {
        return min;
    }
}
